﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QJY.Common;
using QJY.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace QJY.API
{






    #region 流程处理模块

    public class Yan_WF_DaiLiB : BaseEFDao<Yan_WF_DaiLi>
    { }

    public class Yan_WF_TDB : BaseEFDao<Yan_WF_TD>
    {

    }
    public class Yan_WF_PDB : BaseEFDao<Yan_WF_PD>
    {
        /// <summary>
        ///获取流程Id
        /// </summary>
        /// <param name="processId"></param>
        /// <returns></returns>
        public int GetProcessID(string processName)
        {
            return new Yan_WF_PDB().GetEntity(d => d.ProcessName == processName).ID;
        }
    }



    public class Yan_WF_PIB : BaseEFDao<Yan_WF_PI>
    {
        /// <summary>
        /// 添加流程()
        /// </summary>
        /// <param name="strAPPCode"></param>
        /// <param name="strSHR"></param>
        /// <returns>返回创建的第一个任务</returns>
        public Yan_WF_TI StartWF(Yan_WF_PD PD, string strModelCode, string userName, string strSHR, string strCSR, Yan_WF_PI PI, ref List<string> ListNextUser)
        {



            if (PD.ProcessType == "-1")
            {
                ENDWF(PI.ID);
            }//没有流程步骤的,直接结束流程


            //创建流程实例
            Yan_WF_TI TI = new Yan_WF_TI();
            if (PD.ProcessType == "1")//固定流程
            {
                //添加首任务
                TI.TDCODE = PI.PDID.ToString() + "-1";
                TI.PIID = PI.ID;
                TI.StartTime = DateTime.Now;
                TI.EndTime = DateTime.Now;
                TI.TaskUserID = userName;
                TI.TaskUserView = "发起表单";
                TI.TaskState = 1;//任务已结束
                TI.ComId = PD.ComId;
                TI.CRUser = userName;
                TI.CRDate = DateTime.Now;
                new Yan_WF_TIB().Insert(TI);
                //添加首任务
                ListNextUser = AddNextTask(TI);

            }
            return TI;

        }



        /// <summary>
        /// 结束当前任务
        /// </summary>
        /// <param name="TaskID"></param>
        /// <param name="strManAgeUser"></param>
        /// <param name="strManAgeYJ"></param>
        private void ENDTASK(int TaskID, string strManAgeUser, string strManAgeYJ, int Status = 1)
        {
            Yan_WF_TI TI = new Yan_WF_TIB().GetEntity(d => d.ID == TaskID);
            TI.TaskUserID = strManAgeUser;
            TI.TaskUserView = strManAgeYJ;
            TI.EndTime = DateTime.Now;
            TI.TaskState = Status;
            new Yan_WF_TIB().Update(TI);
            new Yan_WF_PIB().ExsSclarSql("UPDATE Yan_WF_TI SET TaskState=" + Status + " WHERE PIID='" + TI.PIID + "' AND TDCODE='" + TI.TDCODE + "'");//将所有任务置为结束状态
        }

        /// <summary>
        /// 结束当前流程
        /// </summary>
        /// <param name="PID"></param>
        public void ENDWF(int PID)
        {
            Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == PID);
            PI.isComplete = "Y";
            PI.CompleteTime = DateTime.Now;
            new Yan_WF_PIB().Update(PI);
        }


        /// <summary>
        /// 添加下一任务节点
        /// </summary>
        /// <param name="PID"></param>
        private List<string> AddNextTask(Yan_WF_TI TI, string strZPUser = "")
        {
            List<string> ListNextUser = new List<string>();
            string strNextTcode = TI.TDCODE.Split('-')[0] + "-" + (int.Parse(TI.TDCODE.Split('-')[1]) + 1).ToString();//获取任务CODE编码,+1即为下个任务编码
            Yan_WF_TD TD = new Yan_WF_TD();
            TD = new Yan_WF_TDB().GetEntity(d => d.TDCODE == strNextTcode);
            if (TD != null)
            {
                Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == TI.PIID);
                if (TD.isSJ == "0")//选择角色时找寻角色人员
                {
                    DataTable dt = new JH_Auth_UserRoleB().GetUserDTByRoleCode(Int32.Parse(TD.AssignedRole), TI.ComId.Value);
                    foreach (DataRow dr in dt.Rows)
                    {
                        Yan_WF_TI Node = new Yan_WF_TI();
                        Node.TDCODE = strNextTcode;
                        Node.PIID = TI.PIID;
                        Node.StartTime = DateTime.Now;
                        Node.TaskUserID = dr["username"].ToString();
                        Node.TaskState = 0;//任务待结束
                        Node.TaskName = TD.TaskName;
                        Node.TaskRole = TD.TaskAssInfo;
                        Node.ComId = TI.ComId;
                        Node.CRDate = DateTime.Now;
                        new Yan_WF_TIB().Insert(Node);
                        ListNextUser.Add(dr["username"].ToString());
                    }
                }
                if (TD.isSJ == "1")//选择上级时找寻上级
                {
                    string Leader = new JH_Auth_UserB().GetUserLeader(PI.ComId.Value, TI.TaskUserID);
                    Yan_WF_TI Node = new Yan_WF_TI();
                    Node.TDCODE = strNextTcode;
                    Node.PIID = TI.PIID;
                    Node.StartTime = DateTime.Now;
                    Node.TaskUserID = Leader;
                    Node.TaskState = 0;//任务待结束
                    Node.TaskName = TD.TaskName;
                    Node.TaskRole = TD.TaskAssInfo;
                    Node.ComId = TI.ComId;
                    Node.CRDate = DateTime.Now;
                    new Yan_WF_TIB().Insert(Node);
                    ListNextUser.Add(Leader);

                }
                if (TD.isSJ == "2")//选择发起人时找寻发起人
                {


                    Yan_WF_TI Node = new Yan_WF_TI();
                    Node.TDCODE = strNextTcode;
                    Node.PIID = TI.PIID;
                    Node.StartTime = DateTime.Now;
                    Node.TaskUserID = PI.CRUser;
                    Node.TaskState = 0;//任务待结束
                    Node.TaskName = TD.TaskName;
                    Node.TaskRole = TD.TaskAssInfo;
                    Node.ComId = TI.ComId;
                    Node.CRDate = DateTime.Now;
                    new Yan_WF_TIB().Insert(Node);
                    ListNextUser.Add(PI.CRUser);
                }
                if (TD.isSJ == "3")//选择指定人员找指定人
                {
                    foreach (string user in TD.AssignedRole.TrimEnd(',').Split(','))
                    {

                        Yan_WF_TI Node = new Yan_WF_TI();
                        Node.TDCODE = strNextTcode;
                        Node.PIID = TI.PIID;
                        Node.StartTime = DateTime.Now;
                        Node.TaskUserID = user;
                        Node.TaskState = 0;//任务待结束
                        Node.TaskName = TD.TaskName;
                        Node.TaskRole = TD.TaskAssInfo;
                        Node.ComId = TI.ComId;
                        Node.CRDate = DateTime.Now;
                        new Yan_WF_TIB().Insert(Node);
                        ListNextUser.Add(user);
                    }
                }
                if (TD.isSJ == "4")//选择绑定字段的值
                {
                    string strGLUser = new Yan_WF_PIB().GetFiledVal(PI.Content, TD.AssignedRole);
                    Yan_WF_TI Node = new Yan_WF_TI();
                    Node.TDCODE = strNextTcode;
                    Node.PIID = TI.PIID;
                    Node.StartTime = DateTime.Now;
                    Node.TaskUserID = strGLUser;
                    Node.TaskState = 0;//任务待结束
                    Node.TaskName = TD.TaskName;
                    Node.TaskRole = TD.TaskAssInfo;
                    Node.ComId = TI.ComId;
                    Node.CRDate = DateTime.Now;
                    new Yan_WF_TIB().Insert(Node);
                    ListNextUser.Add(strGLUser);
                }

            }


            return ListNextUser;

        }
        /// <summary>
        /// 退回当前流程
        /// </summary>
        /// <param name="PID"></param>
        private void REBACKWF(int PID)
        {
            Yan_WF_PI PI = new Yan_WF_PIB().GetEntity(d => d.ID == PID);
            PI.IsCanceled = "Y";
            PI.CanceledTime = DateTime.Now;
            new Yan_WF_PIB().Update(PI);

        }

        /// <summary>
        /// 获取需要处理的任务
        /// </summary>
        /// <param name="strUser">用户需要处理</param>
        /// <returns></returns>
        public List<Yan_WF_TI> GetDSH(JH_Auth_User User)
        {
            List<Yan_WF_TI> ListData = new List<Yan_WF_TI>();

            ListData = new Yan_WF_TIB().GetEntities("ComId ='" + User.ComId.Value + "' AND TaskUserID ='" + User.UserName + "'AND TaskState='0'").ToList();
            return ListData;
        }



        /// <summary>
        /// 判断当前用户当前流程是否可以审批
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public string isCanSP(string strUser, int PIID)
        {
            DataTable dt = new Yan_WF_TIB().GetDTByCommand("SELECT ID FROM  Yan_WF_TI  WHERE PIID='" + PIID + "' AND TaskState='0' AND TaskUserID='" + strUser + "' ");
            return dt.Rows.Count > 0 ? "Y" : "N";
        }


        /// <summary>
        /// 判断用户是否有编辑表单得权限
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public string isCanEdit(string strUser, int PIID)
        {
            DataTable dt = new Yan_WF_TIB().GetDTByCommand("SELECT Yan_WF_TD.isCanEdit FROM  Yan_WF_TI LEFT JOIN   Yan_WF_TD on  Yan_WF_TI.TDCODE=Yan_WF_TD.TDCODE  WHERE PIID='" + PIID + "' AND TaskState='0' AND TaskUserID='" + strUser + "'and isCanEdit='True' ");
            return dt.Rows.Count > 0 ? "Y" : "N";

        }


        /// <summary>
        /// 退回流程
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public bool REBACKLC(string strUser, int PIID, string strYJView)
        {
            try
            {
                Yan_WF_TI MODEL = new Yan_WF_TIB().GetEntities(" PIID='" + PIID + "' AND TaskState='0' AND TaskUserID='" + strUser + "' ").FirstOrDefault();
                if (MODEL != null)
                {
                    ENDTASK(MODEL.ID, strUser, strYJView, -1);//退回
                    REBACKWF(MODEL.PIID);
                }
                return true;
            }
            catch (Exception)
            {

                return false;
            }


        }

        /// <summary>
        /// 处理流程
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public bool MANAGEWF(string strUser, int PIID, string strYJView, ref List<string> ListNextUser, string strShUser)
        {
            try
            {
                Yan_WF_TI MODEL = new Yan_WF_TIB().GetEntities(" PIID='" + PIID + "' AND TaskState='0' AND TaskUserID='" + strUser + "' ").FirstOrDefault();
                if (MODEL != null)
                {
                    ENDTASK(MODEL.ID, strUser, strYJView);
                    ListNextUser = AddNextTask(MODEL, strShUser);
                    //循环找下一个审核人是否包含本人，如果包含则审核通过
                    if (ListNextUser.Contains(strUser))
                    {
                        ListNextUser.Clear();
                        return MANAGEWF(strUser, PIID, strYJView, ref ListNextUser, strShUser);
                    }
                }
                return true;
            }
            catch (Exception)
            {

                return false;
            }


        }

        /// <summary>
        /// 已处理的任务
        /// </summary>
        /// <param name="strUser"></param>
        /// <returns></returns>
        public List<Yan_WF_TI> GetYSH(JH_Auth_User User)
        {
            List<Yan_WF_TI> ListData = new List<Yan_WF_TI>();
            ListData = new Yan_WF_TIB().GetEntities(" ComId ='" + User.ComId.Value + "' AND TaskUserID ='" + User.UserName + "' AND (TaskState=1 OR TaskState=-1) AND TaskUserView!='发起表单'").ToList();
            return ListData;
        }


        public int GETPDID(int PIID)
        {
            Yan_WF_PI pi = new Yan_WF_PIB().GetEntity(d => d.ID == PIID);
            return pi == null ? 0 : pi.PDID.Value;
        }


        /// <summary>
        /// 更具PID获取PD数据
        /// </summary>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public Yan_WF_PD GETPDMODELBYID(int PIID)
        {
            Yan_WF_PD MODEL = new Yan_WF_PD();
            Yan_WF_PI pi = new Yan_WF_PIB().GetEntity(d => d.ID == PIID);
            if (pi != null)
            {
                MODEL = new Yan_WF_PDB().GetEntity(d => d.ID == pi.PDID);
            }

            return MODEL;
        }



        /// <summary>
        /// 根据数据ID进行归档操作
        /// </summary>
        /// <param name="modelCode">modelCode</param>
        /// <param name="PIID">流程的PIID</param>
        /// <returns></returns>
        public void GDForm(string isGD, int ComID, string PIIDS)
        {
            string strSql = string.Format(" UPDATE Yan_WF_PI SET isGD='{0}',GDDate='{1}' where Comid='{2}' AND  ID in ({3})", isGD, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), ComID.ToString(), PIIDS);
            object obj = new Yan_WF_PIB().ExsSclarSql(strSql);

        }


        /// <summary>
        /// 根据数据ID和modelCode更新PIID(新版废弃)
        /// </summary>
        /// <param name="modelCode">modelCode</param>
        /// <param name="PIID">流程的PIID</param>
        /// <returns></returns>
        public string UpdateDataIdByCode(string modelCode, int DATAID, int PIID)
        {
            JH_Auth_Model model = new JH_Auth_ModelB().GetEntity(d => d.ModelCode == modelCode);
            if (model != null)
            {
                string strSql = string.Format(" UPDATE {0} SET intProcessStanceid={1} where ID={2}", model.RelTable, PIID, DATAID);
                object obj = new Yan_WF_PIB().ExsSclarSql(strSql);
                return obj != null ? obj.ToString() : "";
            }
            return "";
        }



        /// <summary>
        /// 根据PIID判断当前流程的数据（）
        /// </summary>
        /// <param name="PIID"></param>
        /// <returns></returns>
        public string GetPDStatus(int PIID)
        {
            Yan_WF_PI Model = new Yan_WF_PIB().GetEntity(d => d.ID == PIID);
            if (Model != null)
            {
                if (Model.isComplete == "Y")
                {
                    return "已审批";
                }
                if (Model.IsCanceled == "Y")
                {
                    return "已退回";
                }

                return "正在审批";
            }
            else
            {
                return "";
            }
        }
        public int GetFormIDbyPID(string strModeCode, int PID)
        {
            int intFormID = 0;

            JH_Auth_Model QYModel = new JH_Auth_ModelB().GetEntity(d => d.ModelCode == strModeCode);
            string strSQL = string.Format("SELECT ID FROM " + QYModel.RelTable + " WHERE  intProcessStanceid='{0}'", PID);
            intFormID = int.Parse(new Yan_WF_PDB().ExsSclarSql(strSQL) == null ? "0" : new Yan_WF_PDB().ExsSclarSql(strSQL).ToString());

            return intFormID;
        }


        /// <summary>
        /// 判断当前用户当前流程是否可以撤回和更新,判断是不是只有一个处理过得节点，或者是自己创建的无流程的表单
        /// </summary>
        /// <param name="strUser"></param>
        /// <param name="PIID"></param>
        /// <returns>返回Y得时候可以撤回,返回不是Y,代表已经处理了不能撤回</returns>
        public string isCanCancel(string strUser, Yan_WF_PI PIMODEL)
        {
            string strReturn = "N";

            DataTable dt = new Yan_WF_TIB().GetDTByCommand("SELECT * FROM  Yan_WF_TI  WHERE PIID='" + PIMODEL.ID + "' AND EndTime IS not null");
            if (dt.Rows.Count == 1 && dt.Rows[0]["TaskUserID"].ToString() == strUser)
            {
                strReturn = "Y";
            }
            if (PIMODEL.CRUser == strUser && PIMODEL.PITYPE == "-1")
            {
                strReturn = "Y";
                //自己创建的无流程的表单
            }

            return strReturn;
        }

        /// <summary>
        /// 生成流水号
        /// </summary>
        /// <param name="PIMODEL"></param>
        /// <returns></returns>
        public string CreateWFNum(string PDID)
        {
            string strReturn = "";
            DataTable dt = new Yan_WF_TIB().GetDTByCommand(" select ISNULL(max(WFFormNum),0) as MAXFORMMUM from Yan_WF_PI WHERE PDID = '" + PDID + "'");
            strReturn = CommonHelp.GetWFNumber(dt.Rows[0][0].ToString(), PDID);
            return strReturn;
        }


        /// <summary>
        /// 从PI数据中获取关联字段的值，主要是关联审批人
        /// </summary>
        /// <param name="Content"></param>
        /// <returns></returns>
        public string GetFiledVal(string Content, string wigdetcode)
        {
            string strReturn = "";
            JArray datas = (JArray)JsonConvert.DeserializeObject(Content);
            foreach (JObject item in datas)
            {
                if ((string)item["wigdetcode"].ToString() == wigdetcode)
                {
                    strReturn = (string)item["value"].ToString();
                }
            }
            return strReturn;
        }



    }

    public class Yan_WF_TIB : BaseEFDao<Yan_WF_TI> { }
    public class SZHL_DRAFTB : BaseEFDao<SZHL_DRAFT> { }

    #endregion





















}
